package streaming.kafka

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

object KafkaLog4j2LogCount {


  def main(args: Array[String]): Unit = {

    if(args.length != 3){
      System.err.println("Usage: KafkaLog4j2LogCount <bootstrapServers> <groupId> <topics>")
      System.exit(1)
    }

    val Array(bootstrapServers,groupId,topics) = args

    val sc = new SparkConf().setMaster("local[*]").setAppName("KafkaLog4j2LogCount")
    val ssc = new StreamingContext(sc,Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> bootstrapServers,
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId,
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val messages = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics.split(",").toArray, kafkaParams)
    )
    messages.map(m=>{
      print(m.value())
    }).count().print()

    ssc.start()
    ssc.awaitTermination()

  }
}
